<?php
// $objResponse->addAlert('Response: I am here!');return $objResponse;
class Register extends Controller 
{
	var $uid;
	var $tpl;

	function setVars()
	{
		$this->uid = (object) $this->session->userdata('uid');
	}
	
	function Register()
	{
		parent::Controller();
		$this->setVars();
		$this->output->enable_profiler(TRUE);
		log_message('debug', "Register: Controler Class Initialized");
	}

	function Menu()
	{
		$menu[] = anchor('/','Home');
		return $menu;
	}

/*****************************************************************\
|               Register User Name
\*****************************************************************/	

	function index() 
	{
		$this->tpl['Messanger'] = 'No New Messages';
		//$this->tpl['tpljs'][]  = '';
		$this->tpl['jsOnLoad']  = '';
		$this->tpl['title'] = "Name";
		$this->tpl['head'] = '';
		$this->tpl['menu'] = $this->Menu();
		$this->tpl['body'] = '';
		$this->tpl['countryOptions'] = $this->country_options();
		$sq = $this->security_options();
		$this->tpl['securityQuestions'] = $sq['Questions'];
		$this->tpl['securityAnswers'] = $sq['Answers'];
		$this->load->library('timetamer');
		//$this->tpl['dtsform'] = $this->timetamer->MakeForm(); //Depriciated
		$this->tpl['captcha'] = $this->captcha_view();

		if(isset($_POST['Alias']))
		{
			$this->postCheck();
		}
		else
		{
			$this->tpl['countryOptions'] = $this->country_options();
			$this->load->view('account/register', $this->tpl);
		}
	}

	function postCheck()
	{
		log_message('debug', "Register: Post check");
		$this->load->library('validation');
		$this->load->model('pdb');
//		$rules['First_Name'] 	= "trim|required|min_length[2]|max_length[100]|xss_clean";
//		$rules['Last_Name']		= "trim|required|min_length[2]|max_length[100]|xss_clean";
		$rules['Alias']			= "trim|required|min_length[5]|max_length[20]|xss_clean";
		$rules['eMail']			= "trim|required|valid_email|xss_clean";
		$rules['ZIP']				= "trim|required|xss_clean";
		$fields['ZIP']    		= '"ZIP/Post Code"';
		$rules['Country']			= "trim|required|xss_clean";
		$fields['Country']    	= 'Country';
		$rules['captcha']    	= "required|callback_captcha_check";
		$fields['captcha']    	= 'Image Code';
		$rules['Question']		= "trim|required|xss_clean";
		$rules['Dance']			= "trim|xss_clean";
		$rules['FacialFuture']	= "trim|xss_clean";
		$rules['Books']			= "trim|xss_clean";
		$rules['MickeyMouse']	= "trim|xss_clean";
		$rules['Dwarfs']			= "trim|xss_clean";
		$rules['Piano']			= "trim|xss_clean";
		$this->validation->set_rules($rules);
		$this->validation->set_fields($fields);
		log_message('debug', "Register: Validation Rules set");
		if ($this->validation->run() == FALSE)
		{
			$this->msg->getMsg();
			$this->load->view('account/register', $this->tpl);
		}
		else
		{
			//Check if email exist in db;
			//$this->db->select('email')->from('Account')->where('eMail', $this->validation->eMail)->limit(1);
			//$account = $this->db->get();
			$emailcheck = $this->pdb->dbGet('user', '?', 'eMail',$this->validation->eMail);
			if ($emailcheck !== FALSE)
			{
				$this->msg->setError('You already have an account with us');
				$this->msg->setMsg('We already have email you your account information.');
				//$this->Account->SendPass($query->alias, $email, $query->pass);
				$this->load->view('account/register', $this->tpl);
			}else{
				$this->load->helper('string');
				$data = array(
               'Alias' 		=> $this->validation->Alias,
               'Pass' 		=> random_string('alnum', 6),
					'TZ' 			=> $this->session->userdata('TZ'),
               'IP' 			=> $this->fun->getip(),
					'First' 		=> 'NOW()'
            );
				$this->db->insert('Auth', $data);
				$uid = $this->db->insert_id();
				//$this->pdb->dbPut('user', $uid, 'eMail',$this->validation->eMail);
				//$this->db->dbPut('user', $uid, 'ZIP',$ZIP);
				//$this->db->dbPut('user', $uid, 'Country',$Country);

				$data = array(
               'uid' => $uid,
             'First_Name' 	=> $this->validation->First_Name,
					'Last_Name' 	=> $this->validation->Last_Name,
					'eMail' 			=> $this->validation->eMail,
               'Country' 		=> $this->validation->Country,
               'ZIP' 			=> $this->validation->ZIP
            );
				$this->db->insert('Account', $data);

				$answer = $this->validation->Question;
				$data = array(
               'cat' 	=> 'user',
               'sub' 	=> 'Security Question',
					'name' 	=> $this->validation->Question,
               'value' 	=> $this->validation->$answer
            );
				$this->db->insert('data', $data);
				$this->load->view('account/user', $this->tpl);
			}
		}
	}
	
   function country_options()
	{
		$output = '<select name="Country">';
		$output .= "<option value=\"\">--Location by Timezone--</option>\n";
		$tz = $this->session->userdata('TZ');
		if(isset($tz))
		{
			$sql = "
			SELECT TZ.id, FIPS, TZ_Linux, Country FROM TZ
			JOIN (Country) ON (TZ.ISO3166 = Country.ISO3166)
			WHERE TZ = '$tz'
			";
		}
		else
		{
			$sql = "
			SELECT TZ.id, FIPS, TZ_Linux, Country FROM TZ
			JOIN (Country) ON (TZ.ISO3166 = Country.ISO3166)
			";
		}
		
		$query = $this->db->query($sql);
		foreach ($query->result() as $row)
		{
			if(isset($tz))
			{
				$l = strstr($row->TZ_Linux, '/');
				$c = $row->Country;
				$c = $c.$l;
			}
			$output .= "<option value=\"$row->FIPS\"";
			$output .= ">$c</option>\n";
		}
		$output .= '</select>'; 
		return $output;		
	}


   	    	 
   function security_options()
	{
		$sql = "SELECT `name` , `value` , `ext`
		FROM `data`
		WHERE `cat` = 'Select'
		AND `sub` = 'Security Question';";
		
		$query = $this->db->query($sql);
		
		$Question = "";
		$Answer = '';
		$Question = '<select name="Question"'; 
		$Question .= "onchange=\"secShowHide(this.options[this.selectedIndex].value)\"
		onmouseover=\"secHide(this.options[this.selectedIndex].value)\">";
		$Question .= "\t<option value=\"\">--Select--</option>\n";
		foreach($query->result() as $row) {
			$row->ext = explode(', ',$row->ext); 
			$Question .= "\t<option value=\"$row->name\"";
				if( $this->input->post('Question') == $row->name ) {
                $Question .= ' selected';
            }
			$Question .= ">$row->value</option>\n";
			$Answer .= "<select id=\"$row->name\" style=\"display: none;\" name=\"$row->name\">\n";
			$Answer .= "\t<option value=\"\">--Select--</option>\n";
			foreach($row->ext as $k => $v) {
				$k++;
				$Answer .= "\t<option value=\"$k\"";
				if( $this->input->post('Answer') == $k ) {
                $Answer .= ' selected';
            }
				$Answer .= ">$v</option>\n";
			}
			$Answer .= "</select>\n";
		}
		$Question .= "</select>\n";

		$return['Questions'] = $Question;
		$return['Answers'] = $Answer;
		return $return;
	}			
		
/*****************************************************************\
|               CAPTCHA
\*****************************************************************/	

	function captcha_view()
	{
		$this->load->plugin('captcha');
		$vals = array(
			'img_path'	 => '/var/www/public/captcha/',
			'img_url'	 => 'http://localhost/public/captcha/',
			'font_path'	 => '/var/www/system/fonts/jester.ttf',
			'img_width'	 => 110,
			'img_height' => 25,
			'expiration' => 360
			);
		
		$cap = create_captcha($vals);
		
		$data = array(
			'captcha_id'	=> '',
			'captcha_time'	=> $cap['time'],
			'ip_address'	=> $this->input->ip_address(),
			'word'			=> $cap['word']
			);
		
		$query = $this->db->insert_string('captcha', $data);
		$this->db->query($query);
		
		//$data  = '<br />Submit the word you see below:<br />';
		$data = $cap['image'];
		//$data .= '<br /><input type="text" name="captcha" />';
		return $data;
	}

	
	function captcha_check()
	{
			// First, delete old captchas
			$expiration = time()-1500;
			$this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
			
			// Then see if a captcha exists:
			$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? ";
			$binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
			$query = $this->db->query($sql, $binds);
			$row = $query->row();
			
			if ($row->count == 0)
			{
				$this->validation->set_message('captcha_check', 'You must submit the word that appears in the image.');
				return FALSE;
			}	
	}
}
?>
